package com.xst.util;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;


public abstract class BaseHibernateDAO {

	private Session session=null;
	
	protected void setSession(Session session)
	{
		this.session=session;
	}
	
	protected Session getSession()
	{
		this.session=HibernateSessionFactory.getSession();
		return this.session;
	}
	protected void closeSession()
	{
		this.session=null;
		HibernateSessionFactory.closeSession();
		
	}
	
	protected Object get(Class clz,java.io.Serializable id){
		Object ret=null;
		Session session=getSession();
		try{
		ret=session.get(clz, id);
		 
		}catch(Exception e)
		{
			e.printStackTrace();
		}finally
		{
			closeSession();
		}
		
		return ret;
	}
	
	protected void addOrUpdate(Object item )
	{
		Transaction tx=null;
		Session session=getSession();
		
		try
		{
			tx=session.beginTransaction();
			session.saveOrUpdate(item);
			tx.commit();
		}catch(Exception e)
		{
			if(null!=tx){tx.rollback();}
			e.printStackTrace();
			
		}finally
		{
			closeSession();
		}

	}
	
//	protected void update(Object item )
//	{
//		Transaction tx=null;
//		Session session=getSession();
//		
//		try
//		{
//			tx=session.beginTransaction();
//			session.update(item);
//			tx.commit();
//		}catch(Exception e)
//		{
//			if(null!=null){tx.rollback();}
//			e.printStackTrace();
//		}finally
//		{
//			closeSession();
//		}
//		
//		
//		
//	}
	
	protected void delete(Class clz,java.io.Serializable id )
	{
		Transaction tx=null;
		Object o=this.get(clz, id);
		Session session=getSession();
		
		try
		{
			tx=session.beginTransaction();
			session.delete(o);
			tx.commit();
			
		}catch(Exception e)
		{
			if(null!=null){tx.rollback();}
			e.printStackTrace();
		}finally
		{
			closeSession();
		}
		
		
		
	}
	
	protected List search(Class clazz,Object condition )
	{
	
		
		try
		{
			List results=getSession().createCriteria(clazz).add(Example.create(condition)).list();
			
			return results;
			
		}catch(RuntimeException re)
		{
			throw re;
		
		}finally
		{
			closeSession();
		}
		
		
		
	}
	
}
